package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import com.auto.learning.R;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.bean.WeChatData;
import com.auto.learning.event.Handle;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.sharesdk.tools.SnsLogin;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class LoginActivity extends BaseActivity implements OnClickListener,Callback {
	
	private final static int LOGIN_SUCCESS = 1;
	private static final int MSG_LOGIN_FAIL = 2;
	private static final int MSG_GET_CODE_SUCCESS = 3;
	private static final int MSG_GET_CODE_FAIL = 4;
	
	ImageView company_login,weixin_login,qq_login,image_backgroup;
	TextView tv_new_user,tv_forget_password,tv_login,tv_code;
	EditText et_phone,et_password;
	
	int totalTime = 60;
	
	String verPhone = "";
	
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case LOGIN_SUCCESS:
				CommonMethod.makeNotice(LoginActivity.this, "登录成功");
				SharedPreferencesUtils.setParam(LoginActivity.this, "loginType", 0);
				ResponeResult result = (ResponeResult) msg.obj;
				UserInfoBean userInfoBean = new Gson().fromJson(result.getData(), new TypeToken<UserInfoBean>(){}.getType());
				if (userInfoBean != null) {
					SharedPreferencesUtils.setParam(LoginActivity.this, HttpRequestHelper.USERID, userInfoBean.getUserId());
					CommonMethod.setAliasAndTags(LoginActivity.this, userInfoBean.getUserId());
					Cache.cacheUserInfo2Local(userInfoBean);
					MyUserInfo.getInstance().setUserInfoBean(userInfoBean);
					setResult(204);
					finish();
				}
				break;
			case MSG_LOGIN_FAIL:
				CommonMethod.makeNotice(LoginActivity.this, (String)msg.obj);
				break;
			case MSG_GET_CODE_SUCCESS:
				et_phone.setEnabled(false);
				tv_code.setEnabled(false);
				handle.postDelayed(runnable, 1000);
				break;
			case MSG_GET_CODE_FAIL:
				CommonMethod.makeNotice(LoginActivity.this, (String)msg.obj);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setViewInLine(R.layout.login_activity);
		initView();
		TemporaryVariable.activities.push(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		TemporaryVariable.activities.removeElement(this);
		super.onDestroy();
	}
	
	private void initView(){
		setTitle(getResources().getString(R.string.login_read));
		hideRight();
		tv_code = (TextView) findViewById(R.id.tv_code);
		image_backgroup = (ImageView) findViewById(R.id.image_backgroup);
		company_login = (ImageView) findViewById(R.id.company_login);
		company_login.setOnClickListener(this);
		tv_new_user = (TextView) findViewById(R.id.tv_new_user);
		tv_new_user.setOnClickListener(this);
		tv_forget_password = (TextView) findViewById(R.id.tv_forget_password);
		tv_forget_password.setOnClickListener(this);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_password = (EditText) findViewById(R.id.et_password);
		tv_login= (TextView) findViewById(R.id.tv_login);
		weixin_login = (ImageView) findViewById(R.id.weixin_login);
		qq_login = (ImageView) findViewById(R.id.qq_login);
		tv_login.setOnClickListener(this);
		weixin_login.setOnClickListener(this);
		qq_login.setOnClickListener(this);
		image_backgroup.setOnClickListener(this);
		tv_code.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.company_login:
			startActivity(CompanyRecommendActivity.class);
			break;
		case R.id.tv_new_user:   //新用户注册
			Intent intent = new Intent(this, RegeditActivity.class);
			intent.putExtra("type", 1);
			startActivity(intent);
			break;
		case R.id.tv_forget_password:  //忘记密码
			Intent intent2 = new Intent(this, RegeditActivity.class);
			intent2.putExtra("type", 2);
			startActivity(intent2);
			break;
		case R.id.tv_login:
			String phone = et_phone.getText().toString();
			String password = et_password.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				CommonMethod.makeNotice(this, getResources().getString(R.string.text_login_phone));
				et_phone.setFocusable(true);
				return;
			}
			if (TextUtils.isEmpty(password)) {
				CommonMethod.makeNotice(this, "验证码不能为空");
				et_password.setFocusable(true);
				return;
			}
			if (CommonMethod.regExpPhone(phone)) {
				loginByCode(phone, password);
			}else {
				CommonMethod.makeNotice(this, getResources().getString(R.string.text_login_phone_reg));
			}
			break;
		case R.id.weixin_login:
			new SnsLogin(this,this).authorize(ShareSDK.getPlatform(Wechat.NAME));
			break;
		case R.id.qq_login:
			new SnsLogin(this,this).authorize(ShareSDK.getPlatform(QQ.NAME));
			break;
		case R.id.image_backgroup:
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
			imm.hideSoftInputFromWindow(et_phone.getWindowToken(), 0);
			break;
		case R.id.tv_code:
			String mPhone = et_phone.getText().toString();
			if (TextUtils.isEmpty(mPhone)) {
				CommonMethod.makeNotice(LoginActivity.this, "手机号不能为空");
				return;
			}
			if (CommonMethod.regExpPhone(mPhone)) {
				verPhone = mPhone;
				getVerCode(mPhone);
			}else {
				CommonMethod.makeNotice(this, getResources().getString(R.string.text_login_phone_reg));
			}
			break;
		}
	}
	
	Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			if (totalTime > 0) {
				tv_code.setText("重新获取"+totalTime+"s");
				totalTime--;
				handle.postDelayed(this, 1000);
			}else {
				totalTime = 60;
				et_phone.setEnabled(true);
				tv_code.setEnabled(true);
				tv_code.setText("获取验证码");
			}
		}
	};
	
	public void getVerCode(final String tel){
		Pool.getPool().execute(new Runnable() {
			@Override
			public void run() {
				HttpRequestHelper.getVerCode(LoginActivity.this, handle, tel, 4, MSG_GET_CODE_SUCCESS, MSG_GET_CODE_FAIL);
			}
		});
	}
	
	
	/**
	 * @param toClass
	 */
	private void startActivity(Class toClass) {
		Intent intent = new Intent(this, toClass);
		startActivity(intent);
	}
	
	/**
	 * 登录
	 * @param phone
	 * @param password
	 */
	private void login(String phone,String password){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("tel", phone));
		params.add(new BasicNameValuePair("pwd", password));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.LOGIN, params, handle, LOGIN_SUCCESS,MSG_LOGIN_FAIL);
	}
	
	/**
	 * 短信验证登录
	 * @param code
	 */
	private void loginByCode(String phone,String code){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("tel", phone));
		params.add(new BasicNameValuePair("code", code));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.CODE_LOGIN, params, handle, LOGIN_SUCCESS,MSG_LOGIN_FAIL);
	}
	

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		  case SnsLogin.MSG_AUTH_COMPLETE: 
			CommonMethod.makeNotice(this,getString(R.string.auth_complete));
			WeChatData weChatData = (WeChatData) msg.obj;
			Intent data = new Intent();
			data.putExtra("userId", weChatData.getUserId());
			data.putExtra("nickName", weChatData.getNickname());
			data.putExtra("headImgUrl", weChatData.getHeadimgurl());
			data.putExtra("isweixin", weChatData.getPlat() == 0);
			setResult(203,data);
			finish();
			break;
		}
		return false;
	}
}
